#!/usr/bin/perl

# This file is part of noplagia.
#
# noplagia is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# noplagia is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# noplagia; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA  02111-1307 USA


=head1 NAME

    noplagia.pl

=head1 SYNOPSIS

    Execute les taches en attentes. Script prevu pour etre execute automatiquement a periode reguliere.

=cut

use strict;
use warnings;
use lib ('./lib');

use lib::Context;
#use CGI;
#use lib::In;
use lib::Noplagia;
use WWW::Mechanize;
use Data::Dumper;
use lib::TextTreatment;
use lib::Context;
use IO::LockedFile ( block => 0 );

#Fichier verrou pour n'effectuee qu'une tache a la fois
my $lock_file = new IO::LockedFile(">/tmp/noplagia-pl_locked.txt");

if (not $lock_file) {
	die 'Une tache est deja en cours d execution';
}
if (not exists $ENV{"NOPLAGIA_CONF"}) {
	die "attention a bien faire l'export de NOPLAGIA_CONF";
}

# connexion a la base de donnee pour recuperer la tache a executer.
# Gestion FIFO
lib::Context::set_conn_db;
my $schema = &get_dbh;
my $task = $schema->resultset('TaskQueue')->find({},{order_by => 'id'});
if (not $task) {
	die "pas de tache a executer";
} else {
	warn "une tache a executer";
}

my $file = $schema->resultset('Files')->find({id => $task->id});

my $text = $file->content;
    # --------------------------------
    # -2- heuristique de decoupage
    # --------------------------------
    use lib::SplitText;

    # decoupage tous les 15 mots
    my $text_to_search = &decoupe_par_chaine($text,&get_pref('longueur_requete'), &get_pref('max_requete'));


    # --------------------------------
    # -3- Envoie des requetes
    # --------------------------------
    use lib::Req;
    my $text_langage = &get_language;
    my @results;
    foreach my $text_offset (@$text_to_search){
        my $inner_result = request(
            {
                engine => "Yahoo",
                count  => "".get_pref('nb_results_engine'),
                lang   => $text_langage,
                text_offset => $text_offset,
            }
        );
        foreach (@$inner_result){
            push @results, $_;
        }
    }

    # --------------------------------
    # -4- Traitement des resultats
    # --------------------------------
    use lib::ResultTreatment;
    my $results_treated = &result_treatment(\@results);

    # --------------------------------
    # -5- Fouille des sites interressants
    # --------------------------------
    use lib::Wget;
    $results_treated = wget($results_treated);

    # --------------------------------
    # -6- Comparaison du site et du local
    # --------------------------------
    use lib::Compare;
    my $parse;
    ($results_treated, $parse) = compare($results_treated, $text);

    # --------------------------------
    # -7- Mise en formes des resulats
    # --------------------------------
    $results_treated = Data::Dumper->new([$results_treated], [qw(results_treated)]);
    $parse           = Data::Dumper->new([$parse], [qw(parse)]);

#on met le rapport dans la bdd
$file->update(
    {
        report => $results_treated->Dump,
        content => $parse->Dump,
    }
);


#on supprime la tache effectuee
$task->delete;

#on envoi un mail

if(get_pref('alert_report_by_mail')){
    use Email::Send;
    my $mail = $file->users->email;
    goto END unless $mail;
    goto END unless get_pref('smtp');
    my $id= $file->id;
    my $nom = $file->nom;
my $message =<<eof;
To: $mail
From: no-reply\@noplagia.org
Content-Type: text/plain; charset='utf-8'
Subject: Compte rendu num $id - $nom

Un nouveau compte rendu est pret. Pour le consulter connectez vous a votre compte sur noplagia.org.
--
Noplagia Team
eof

    my $sender = Email::Send->new({mailer => 'SMTP'});
    $sender->mailer_args([Host => get_pref('smtp')]);
    $sender->send($message);
}

END:
$lock_file->close();

